package com.yinkgh.config;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class MyBatisConfig {
	
	// 也可以在sqlSessionFactoryBean方法 加参数sqlSessionFactoryBean(DataSource dataSource)
	@Autowired
	private DataSource dataSource; 
	
	@Bean
	@ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象

	public SqlSessionFactoryBean sqlSessionFactoryBean() {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		// 设置一系列的参数
		// 数据源 - c3p0或者durid等开源数据源框架
		// sqlSessionFactoryBean.setDataSource(dataSource);
		// 设置数据源
		sqlSessionFactoryBean.setDataSource(dataSource);
		// 设置mybatis的主配置文件
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
		sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
		// 设置别名包 
//		sqlSessionFactoryBean.setTypeAliasesPackage("com.taotao.cart.pojo");

		return sqlSessionFactoryBean;
	}
}
